﻿Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports GuildCMS.Common

Namespace Account
    Public Class Retrieve
        Inherits System.Web.UI.Page

#Region " Database variables "

        ''' <summary>
        ''' Set the database connection variables used throughout this class.
        ''' </summary>
        ''' <remarks>Placed here so they will not need to be typed out each time they are needed.</remarks>
        Private connectionString As String = WebConfigurationManager.ConnectionStrings("SqlConnectionString").ConnectionString()
        Private connection As SqlConnection = New SqlConnection(connectionString)
        Private command As New SqlCommand

#End Region

#Region " Page events "

        ''' <summary>
        ''' Handles the Load event of the Page control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        End Sub

#End Region

#Region " Click event for when the retrieval form is submitted. "

        ''' <summary>
        ''' Handles the Click event of the btnSubmit control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
            ' Figure out if the visitor is retrieving either their login name or requesting a password reset.
            If Not txtLogin.Text = "" Then
                ' Validate the supplied login server side as well as check that it exists within the database.
                If CheckLogin(txtLogin.Text) = True Then
                    ' The supplied login exists so send an email containing an activation code.
                    ' Generate a new code...
                    ' Get email address from the database associated with this login...

                    ' Send this email.
                    'SendMail(email, CStr(GetSetting("EmailSubjectRetrieve")), GenerateBody(ResetPassword, email, login, code))
                Else
                    ' Since the supplied login either failed validation checks or no matching login exists within the database display the form again.

                End If

            ElseIf Not txtEmail.Text = "" Then
                ' Validate the supplied email server side as well as if it exists within the database.
                If CheckEmail(txtEmail.Text) = True Then
                    ' If the supplied email address exists send the visitors login via email.
                    ' Get login from the database...

                    ' Send this email.
                    'SendMail(txtEmail.Text, CStr(GetSetting("EmailSubjectRetrieve")), GenerateBody(SendLogin, txtEmail.Text, login, code))
                Else
                    ' Since the supplied email address either failed validation or does not exist in the database display the form again.

                End If
            Else
                ' The user failed to supply either item so display the form again.

            End If
        End Sub

#End Region

#Region " Form validation functions. "

        ''' <summary>
        ''' Checks the login supplied via the form.
        ''' </summary>
        ''' <param name="login">The login supplied via the form.</param>
        ''' <returns>True or false if the login passed server side checks.</returns>
        Private Function CheckLogin(ByVal login As String) As Boolean
            ' Check that a usable login was entered.
            Dim loginPassed As Boolean = True

            ' Check that the supplied login is alphanumeric.
            Dim loginRegex As New Regex("[a-zA-Z0-9_]")
            If login = "" Then
                loginPassed = False
            Else
                loginPassed = loginRegex.IsMatch(login)
            End If

            ' Check the length of the login supplied
            If login.Length() > 25 Or login.Length() < 3 Then
                loginPassed = False
            End If

            ' Check that the login does not already exist within the database.
            Try
                command = New SqlCommand("sp_public_countLogins", connection)
                command.CommandType = CommandType.StoredProcedure
                command.Parameters.Add("@Login", SqlDbType.NVarChar, 25)
                command.Parameters("@Login").Value = login
                command.Parameters.Add("@Total", SqlDbType.Int)
                command.Parameters("@Total").Direction = ParameterDirection.Output
                connection.Open()
                command.ExecuteNonQuery()
                Dim totalRows As Integer = CInt(command.Parameters("@Total").Value)
                connection.Close()
                If totalRows > 0 Then
                    loginPassed = False
                End If
            Catch ex As Exception
                ' If there was an issue getting this information from the database fail the test.
                loginPassed = False
            End Try

            ' Return the result.
            Return loginPassed
        End Function

        ''' <summary>
        ''' Checks to make sure a valid e-mail address has been entered.
        ''' </summary>
        ''' <param name="emailAddress">The email address sent in the email address textbox.</param>
        ''' <returns>True or false if the supplied email passes server side checks.</returns>
        Private Function CheckEmail(ByVal emailAddress As String) As Boolean
            ' Check that a vaild email was entered.
            Dim emailPassed As Boolean = True

            ' Check that a valid e-mail was entered using a regular expression.
            Dim emailRegex As New Regex("^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")
            If emailAddress = "" Then
                emailPassed = False
            Else
                emailPassed = emailRegex.IsMatch(emailAddress)
            End If

            ' Check the length of the email address supplied.
            If emailAddress.Length > 100 Then
                emailPassed = False
            End If

            ' Check that the supplied email address does not already exist within the database.
            Try
                command = New SqlCommand("sp_public_countEmails", connection)
                command.CommandType = CommandType.StoredProcedure
                command.Parameters.Add("@Email", SqlDbType.NVarChar, 100)
                command.Parameters("@Email").Value = emailAddress
                command.Parameters.Add("@Total", SqlDbType.Int)
                command.Parameters("@Total").Direction = ParameterDirection.Output
                connection.Open()
                command.ExecuteNonQuery()
                Dim totalRows As Integer = CInt(command.Parameters("@Total").Value)
                connection.Close()
                If totalRows > 0 Then
                    emailPassed = False
                End If
            Catch ex As Exception
                ' If there was an issue getting this information from the database fail the test.
                emailPassed = False
            End Try

            ' Return the result.
            Return emailPassed
        End Function

#End Region

#Region " Retrieval e-mail specific functions and procedures. "

        ''' <summary>
        ''' Generates the body for this email message.
        ''' </summary>
        ''' <param name="setting">The setting related to the request being dealt with.</param>
        ''' <param name="code">The activation code generated earlier.</param>
        ''' <returns>The body of the registration activation e-mail.</returns>
        Private Function GenerateBody(ByVal action As String, ByVal email As String, ByVal login As String, ByVal code As String) As String
            ' Retreive the e-mail body template from the database.
            Dim body As String = Nothing

            ' Prepare the email body depending on the type of request made.
            If action = "ResetPassword" Then
                ' Get the correct email template from the database.
                body = CStr(GetSetting("EmailBodyResetPass"))

                ' Replace special strings with dynamically generated ones for a password reset request.
                body = body.Replace("[[CODE]]", code)
                body = body.Replace("[[RESETURL]]", Request.ServerVariables("SERVER_NAME") & "/Reset.aspx?email=" & email & "&code=" & code)
            Else
                ' Get the correct email template from the database.
                body = CStr(GetSetting("EmailBodyRetrieveLogin"))

                ' Replace special strings with dynamically generated ones for a login request request.
                body = body.Replace("[[LOGIN]]", login)
            End If

            ' Return the message body.
            Return body
        End Function

#End Region

    End Class
End Namespace